//
//  PosDetailViewController.m
//  NewPro
//
//  Created by RYX on 2018/11/1.
//  Copyright © 2018年 何荧红. All rights reserved.
//

#import "PosDetailViewController.h"
#import "PosApplyList.h"
#import "PosApplyModel.h"
#import "OrderCenterViewController.h"
#import "MineStore.h"
#import "UserModel.h"
#import "PosApplyList.h"
#import "PosApplyModel.h"
#import "PosApplyStore.h"
#import "ConfirmOrderViewController.h"
#import "MyRedenvelopesList.h"

@interface PosDetailViewController ()<UITextFieldDelegate>
{
    
    __weak IBOutlet UIImageView *iconumg;
    
    __weak IBOutlet UIImageView *im;
    
    __weak IBOutlet NSLayoutConstraint *imtotop;
    
    __weak IBOutlet NSLayoutConstraint *imheight;
    
    __weak IBOutlet NSLayoutConstraint *imwidth;
    
    __weak IBOutlet NSLayoutConstraint *blueViewtotop;
    
    __weak IBOutlet UILabel *la1;
    
    __weak IBOutlet UILabel *la2;

    
    __weak IBOutlet UILabel *la21; //
    
    __weak IBOutlet UILabel *la22; //
    
    __weak IBOutlet UILabel *minla; //
    
    __weak IBOutlet UILabel *restla; //
    
    __weak IBOutlet UILabel *la4;
    
    __weak IBOutlet NSLayoutConstraint *la41totop;
    
    __weak IBOutlet UILabel *la41;  //
    
    __weak IBOutlet UILabel *la3;   //
    
    __weak IBOutlet UILabel *la31;  //
    
    __weak IBOutlet UILabel *la32;  //
    
    __weak IBOutlet NSLayoutConstraint *TopTolabel; //
    
    __weak IBOutlet UILabel *la5;

    __weak IBOutlet UILabel *la6;
    
    __weak IBOutlet UILabel *la7;
    
    __weak IBOutlet UILabel *la8;
    
    __weak IBOutlet UILabel *typeLa;
    
    __weak IBOutlet UITextField *numText;
    
    __weak IBOutlet UILabel *priceLa;
    
    __weak IBOutlet UILabel *timeleft;
    
    __weak IBOutlet UILabel *timela;
    
    __weak IBOutlet UILabel *timeright;
    
    __weak IBOutlet UIButton *reducebtn;
    
    __weak IBOutlet NSLayoutConstraint *graytotop;
    
    
    __weak IBOutlet UIButton *ChooseButton;
    
}
@property (nonatomic, strong) PosApplyModel *model;
@property (nonatomic, assign) NSInteger chooseNumber;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topMargin;

@end

@implementation PosDetailViewController

- (void)setChooseNumber:(NSInteger)chooseNumber{
    _chooseNumber = chooseNumber;
    if (_chooseNumber <= 1 ) {
        [reducebtn setImage:[UIImage imageNamed:@"机具申领减号"] forState:UIControlStateNormal];
        _chooseNumber = 1;
    }else{
        [reducebtn setImage:[UIImage imageNamed:@"机具申领深色减号"] forState:UIControlStateNormal];
    }
    if ([_model.price integerValue] <= 0) {
        priceLa.text = [NSString stringWithFormat:@"¥%.2f",[_model.price floatValue] * _chooseNumber];
    }else{
        priceLa.text = [NSString stringWithFormat:@"¥%ld",[_model.price integerValue] * _chooseNumber];
    }
    numText.text = [NSString stringWithFormat:@"%ld",_chooseNumber];
    if (self.VCType == 2) {
        if (_model.rules.count > 0) {
            NSInteger allcount = _chooseNumber * [_model.number integerValue];
            for (NSDictionary *dic in _model.rules) {
                if ([[NSString stringWithFormat:@"%@",dic[@"maxCount"]]  isEqualToString:@"-1"]) {
                    if (allcount >= [dic[@"minCount"] integerValue]) {
                        timela.text = [NSString stringWithFormat:@"有效期%@天",dic[@"expireTime"]];
                    }
                }else{
                    if (allcount >= [dic[@"minCount"] integerValue] && allcount <= [dic[@"maxCount"] integerValue]) {
                        timela.text = [NSString stringWithFormat:@"有效期%@天",dic[@"expireTime"]];
                    }
                }
            }
        }else{
            timela.text = [NSString stringWithFormat:@"有效期%@天",_model.untilDay];
        }
    }else{
        if (_chooseNumber >= 100) {
            la8.text = @"快递费：顺丰包邮";
        }else{
            la8.text = @"快递费：顺丰到付";
        }
    }
}
-(void)setModel:(PosApplyModel *)model{
    _model = model;
    if (self.VCType == 2) {
        imtotop.constant = 55;
        imheight.constant = 145;
        imwidth.constant = 77;
        blueViewtotop.constant = 56;
        iconumg.hidden = NO;
        la5.hidden = NO;
        la2.hidden = NO;
        timeleft.hidden = NO;
        timela.hidden = NO;
        timeright.hidden = NO;
        la41totop.constant = 9;
        graytotop.constant = 15;
        [ChooseButton setTitle:@"交纳押金" forState:UIControlStateNormal];
        la4.textColor = [UIColor colorWithHexString:@"00A0E9"];
        
        [PosApplyList sharedInstance].selectedPosModel = _model;
        
        if (_model) {
            [im sd_setImageWithURL:[NSURL URLWithString:_model.imgPath]];
            if ([_model.name containsString:@"（"]) {
                NSArray *arr = [_model.name componentsSeparatedByString:@"（"];
                la1.text = [NSString stringWithFormat:@"%@ %@",arr[0],[arr[1] substringWithRange:NSMakeRange(0, [arr[1] length] - 1)]];
                typeLa.text = [NSString stringWithFormat:@"%@ %@",arr[0],[arr[1] substringWithRange:NSMakeRange(0, [arr[1] length] - 1)]];
            }else{
                la1.text = _model.name;
                typeLa.text = _model.name;
            }
            la2.text = _model.sellName;
            minla.text = [NSString stringWithFormat:@"发货%@",_model.singleShipPurchase];
            restla.text = [NSString stringWithFormat:@"%@后发余货",_model.afterActivation];
            la41.text = _model.backDesc;
            la5.text = _model.actTimeDesc;
            la6.text = _model.price;
            la7.text = [NSString stringWithFormat:@"/%@台",_model.number];
            la8.text = [NSString stringWithFormat:@"快递费：¥%.2f元",[_model.expressCost floatValue]];
            priceLa.text = [NSString stringWithFormat:@"¥%@",_model.price];
            if ([_model.singleShipPurchase isEqualToString:@""] && [_model.afterActivation isEqualToString:@""]) {
                la4.text = _model.actDescription;
                
                la21.hidden = YES;
                la22.hidden = YES;
                minla.hidden = YES;
                restla.hidden = YES;
                
                la3.hidden = YES;
                la31.hidden = YES;
                la32.hidden = YES;
                
                TopTolabel.constant = -15;
            }else{
                la4.text = _model.freezeDesc;
                
                la21.hidden = NO;
                la22.hidden = NO;
                minla.hidden = NO;
                restla.hidden = NO;
                
                la3.text = _model.activeDesc;
                la3.hidden = NO;
                la31.hidden = NO;
                la32.hidden = NO;
                
                TopTolabel.constant = 14;
            }
            if (_model.rules.count > 0) {
                NSInteger allcount = _chooseNumber * [_model.number integerValue];
                for (NSDictionary *dic in _model.rules) {
                    if ([[NSString stringWithFormat:@"%@",dic[@"maxCount"]]  isEqualToString:@"-1"]) {
                        if (allcount >= [dic[@"minCount"] integerValue]) {
                            timela.text = [NSString stringWithFormat:@"有效期%@天",dic[@"expireTime"]];
                        }
                    }else{
                        if (allcount >= [dic[@"minCount"] integerValue] && allcount < [dic[@"maxCount"] integerValue]) {
                            timela.text = [NSString stringWithFormat:@"有效期%@天",dic[@"expireTime"]];
                        }
                    }
                }
            }else{
                timela.text = [NSString stringWithFormat:@"有效期%@天",_model.untilDay];
            }
        }
        
        if (_model.categoryId == 2) {
            
            la21.hidden = NO;
            TopTolabel.constant = 14;
            la21.text = _model.des;
            la4.text = _model.freezeDesc;
            la41.text = _model.activeDesc;
            la41.textColor = UIColor.redColor;
        }
        
    }else if (self.VCType == 1){
        imtotop.constant = 49;
        imheight.constant = 140;
        imwidth.constant = 144;
        
        blueViewtotop.constant = 70;
        iconumg.hidden = YES;
        la5.hidden = YES;
        la2.hidden = YES;
        timeleft.hidden = YES;
        timela.hidden = YES;
        timeright.hidden = YES;
        la41totop.constant = 15;
        graytotop.constant = 36;
        [ChooseButton setTitle:@"立即购买" forState:UIControlStateNormal];
        la4.textColor = [UIColor colorWithHexString:@"5A5E66"];
        
        [PosApplyList sharedInstance].selectedPosModel = _model;
        if (_model) {
            [im sd_setImageWithURL:[NSURL URLWithString:_model.imgPath]];
            if ([_model.name containsString:@"（"]) {
                NSArray *arr = [_model.name componentsSeparatedByString:@"（"];
                la1.text = [NSString stringWithFormat:@"%@ %@",arr[0],[arr[1] substringWithRange:NSMakeRange(0, [arr[1] length] - 1)]];
                typeLa.text = [NSString stringWithFormat:@"%@ %@",arr[0],[arr[1] substringWithRange:NSMakeRange(0, [arr[1] length] - 1)]];
            }else{
                la1.text = _model.name;
                typeLa.text = _model.name;
            }
            la41.text = _model.actTimeDesc;
            la6.text = _model.price;
            la7.text = @"/张";
            la8.text = @"快递费：顺丰到付";
            priceLa.text = [NSString stringWithFormat:@"¥%@",_model.price];
            if ([_model.singleShipPurchase isEqualToString:@""] && [_model.afterActivation isEqualToString:@""]) {
                la4.text = _model.actDescription;
                
                la21.hidden = YES;
                la22.hidden = YES;
                minla.hidden = YES;
                restla.hidden = YES;
                
                la3.hidden = YES;
                la31.hidden = YES;
                la32.hidden = YES;
                
                TopTolabel.constant = -15;
            }else{
                la4.text = _model.freezeDesc;
                
                la21.hidden = NO;
                la22.hidden = NO;
                minla.hidden = NO;
                restla.hidden = NO;
                
                la3.text = _model.activeDesc;
                la3.hidden = NO;
                la31.hidden = NO;
                la32.hidden = NO;
                
                TopTolabel.constant = 14;
            }
        }
    }
}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    [MyRedenvelopesList sharedInstance].selectedRedenvelopes = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavBarWithTitle:@"产品详情"];
    [self loadData];
}
- (void)loadData{
    
    self.chooseNumber = 1;
    [[[PosApplyStore alloc]init] getPosDetailWithID:[PosApplyList sharedInstance].selectedPosModel.uid Success:^(PosApplyModel *model) {
        self.model = model;
    } Failure:^(NSError *error) {
        [self showMBPError:[HttpTool handleError:error]];
    }];
}

// 时间戳转时间,时间戳为13位是精确到毫秒的，10位精确到秒
- (NSString *)getDateStringWithTimeStr:(NSString *)str{
    
    NSTimeInterval time = [str doubleValue]/1000;
    
    //传入的时间戳str如果是精确到毫秒的记得要/1000
    
    NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //实例化一个NSDateFormatter对象 //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy年MM月dd"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
    
    return currentDateStr;
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if ([textField.text isEqualToString:@""]) {
        textField.text = @"1";
    }
    self.chooseNumber = [textField.text integerValue];
}
#pragma mark 减号
- (IBAction)Reduce:(UIButton *)sender {
    NSInteger number = [numText.text integerValue];
    number -= 1;
    self.chooseNumber = number;
}
#pragma mark 加号
- (IBAction)AddAction:(UIButton *)sender {
    NSInteger number = [numText.text integerValue];
    number += 1;
    self.chooseNumber = number;
}
#pragma mark - 我的订单
- (IBAction)onMyOrderBtn:(UIButton *)sender {
    OrderCenterViewController *VC = [[OrderCenterViewController alloc] init];
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - 交纳押金
- (IBAction)onPostMoney:(UIButton *)sender {
    
    MineStore *store = [[MineStore alloc] init];
    
    MJWeakSelf
    [store getUserInfoWithCustomId:[UserDefaultsManager sharedInstance].user_id Success:^(UserModel *model) {
        if( ![model.isRealNameAuthenticationed isEqualToString:@"1"]){
            return  [self.view makeToast:@"您尚未进行实名认证" duration:2.0 position:CSToastPositionBottom];
        }
        ConfirmOrderViewController *VC = [[ConfirmOrderViewController alloc] init];
        VC.AllPrice = [self->priceLa.text substringWithRange:NSMakeRange(1, self->priceLa.text.length - 1)];
        VC.Allcount = self->numText.text;
        VC.VCType = self.VCType;
        if (self.VCType == 1) {
            VC.PType = [self->la8.text substringWithRange:NSMakeRange(4, 4)];
        }
        [self.navigationController pushViewController:VC animated:YES];
        
    } Failure:^(NSError *error) {
        
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}

//model转化为字典
- (NSDictionary *)dicFromObject:(NSObject *)object {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    unsigned int count;
    objc_property_t *propertyList = class_copyPropertyList([object class], &count);
    
    for (int i = 0; i < count; i++) {
        objc_property_t property = propertyList[i];
        const char *cName = property_getName(property);
        NSString *name = [NSString stringWithUTF8String:cName];
        NSObject *value = [object valueForKey:name];//valueForKey返回的数字和字符串都是对象
        
        if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]]) {
            //string , bool, int ,NSinteger
            [dic setObject:value forKey:name];
            
        } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
            //字典或字典
            [dic setObject:[self arrayOrDicWithObject:(NSArray*)value] forKey:name];
            
        } else if (value == nil) {
            //null
            //[dic setObject:[NSNull null] forKey:name];//这行可以注释掉?????
            
        } else {
            //model
            [dic setObject:[self dicFromObject:value] forKey:name];
        }
    }
    
    return [dic copy];
}

//将可能存在model数组转化为普通数组
- (id)arrayOrDicWithObject:(id)origin {
    if ([origin isKindOfClass:[NSArray class]]) {
        //数组
        NSMutableArray *array = [NSMutableArray array];
        for (NSObject *object in origin) {
            if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]]) {
                //string , bool, int ,NSinteger
                [array addObject:object];
                
            } else if ([object isKindOfClass:[NSArray class]] || [object isKindOfClass:[NSDictionary class]]) {
                //数组或字典
                [array addObject:[self arrayOrDicWithObject:(NSArray *)object]];
                
            } else {
                //model
                [array addObject:[self dicFromObject:object]];
            }
        }
        
        return [array copy];
        
    } else if ([origin isKindOfClass:[NSDictionary class]]) {
        //字典
        NSDictionary *originDic = (NSDictionary *)origin;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        for (NSString *key in originDic.allKeys) {
            id object = [originDic objectForKey:key];
            
            if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]]) {
                //string , bool, int ,NSinteger
                [dic setObject:object forKey:key];
                
            } else if ([object isKindOfClass:[NSArray class]] || [object isKindOfClass:[NSDictionary class]]) {
                //数组或字典
                [dic setObject:[self arrayOrDicWithObject:object] forKey:key];
                
            } else {
                //model
                [dic setObject:[self dicFromObject:object] forKey:key];
            }
        }
        
        return [dic copy];
    }
    
    return [NSNull null];
}
@end
